package com.css.devops.service.jenkins;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.css.devops.component.JenkinsBasicComponent;
import com.css.devops.constants.DevopsConstants;
import com.css.devops.domain.BuildResult;
import com.css.devops.domain.JobBuild;
import com.css.devops.domain.vo.PipelineMonitorQueryCriteria;
import com.css.devops.service.DevopsJobBuild;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * Job Build(任务构建) 相关操作
 *
 * 例如对任务 Build 相关的信息进行获取操作、例如获取构建日志
 */
@Slf4j
@Service("jenkinsJobBuildService")
public class JenkinsJobBuildService implements DevopsJobBuild {

	
	@Autowired
	private JenkinsBasicComponent jenkinsBasicComponent;
	
    /**
     * 获取 Job 最后的 Build
     */
    @Override
	public JobBuild getJobLastBuild(PipelineMonitorQueryCriteria pipelineMonitorQueryCriteria){
    	String buildUrl = String.format(DevopsConstants.JENKINS_JOB_LAST_BUILD, pipelineMonitorQueryCriteria.getPipeline(), pipelineMonitorQueryCriteria.getBranch());
    	HttpResponse response = jenkinsBasicComponent.getRequest(buildUrl);
    	return parseAndXml(response.body());
    }
    
    /**
     * 解析xml并后返回构建实体结果
     * @param xmlResponse
     * @return
     */
    private JobBuild parseAndXml(String xmlResponse) {
    	JobBuild jobBuild = new JobBuild();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(new InputSource(new StringReader(xmlResponse)));

	        // 解析 XML 数据
	        NodeList resultNodes = document.getElementsByTagName("result");
	        NodeList urlNodes = document.getElementsByTagName("url");
	        NodeList timestampNodes = document.getElementsByTagName("timestamp");
	        NodeList numberNodes = document.getElementsByTagName("number");
	        NodeList displayNameNodes = document.getElementsByTagName("displayName");
	        NodeList durationNodes = document.getElementsByTagName("duration");
	        NodeList fullDisplayNameNodes = document.getElementsByTagName("fullDisplayName");

	        if (resultNodes.getLength() > 0 && urlNodes.getLength() > 0) {
	            String result = resultNodes.item(0).getTextContent();
	            String url = urlNodes.item(0).getTextContent();
	            String timestamp = timestampNodes.getLength() > 0 ? timestampNodes.item(0).getTextContent() : "";
	            String buildNumber = numberNodes.item(0).getTextContent();
	            String displayName = displayNameNodes.item(0).getTextContent();
	            DateTime datetime = StringUtils.isNotEmpty(timestamp) ? DateUtil.date(Long.valueOf(timestamp)) : DateUtil.date();
	            String duration = durationNodes.item(0).getTextContent();
	            String fullDisplayName = fullDisplayNameNodes.item(0).getTextContent();
	            
	            jobBuild.setDisplayName(displayName);
	            jobBuild.setDuration(duration);
	            jobBuild.setFullDisplayName(fullDisplayName);
	            jobBuild.setNumber(buildNumber);
	            jobBuild.setResult(BuildResult.getBuildResult(result));
	            jobBuild.setStartTime(datetime.toString());
	            jobBuild.setUrl(url);
	        }
		} catch (ParserConfigurationException | SAXException | IOException e) {
			log.error(e.getMessage(), e);
		}
        return jobBuild;
    }
}
